<template>
	<view class="consent">
		<view class="top f f-a-c f-j-b">
			<view style="width: 80%;" class="f f-a-c">
				<image src="/static/ziyuan/sech.png" class="sousuo" mode=""></image>
				<input type="text" v-model="value" @confirm="sech" class="inp" name="" id="">
			</view>
			<view @click="sech" class="sceh f f-a-c f-j-c">
				搜索
			</view>
		</view>
		<view class="center f  f-w-w">
			<view class="item f f-a-c f-j-c" v-for="(item, index) in list" :key="index" :class="{ seltImg: item.show }"
				@click="toggleSelect(index)">
				<image src="/static/ziyuan/dui.png" class="dui" v-show="item.show" mode=""></image>
				<view class="content">
					<!-- 标题 -->
					<view class="poem-title">
						<text v-for="(part, index) in parseHtmlText(item.title)" :key="index"
							:class="part.isHighlight ? 'highlight-text' : ''">{{ part.text }}</text>
					</view>
					<!-- 作者朝代 -->
					<view class="poem-author">
						<text v-for="(part, index) in parseHtmlText(item.author)" :key="index"
							:class="part.isHighlight ? 'highlight-text' : ''">{{ part.text }}</text>
					</view>
					<!-- 内容按逗号句号分行 -->
					<view class="poem-content">
						<view class="poem-line f f-a-c f-j-c" v-for="(line, lineIndex) in splitContent(item.content)"
							:key="lineIndex">
							<text v-for="(part, index) in parseHtmlText(line)" :key="index"
								:class="part.isHighlight ? 'highlight-text' : ''">{{ part.text }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view v-if="list.length == 0" style="margin-top: 300rpx;text-align: center;font-size: 36rpx;color: aliceblue;"
			class="">
			<u-empty text="暂无内容" mode="data"></u-empty>
		</view>
		<view class="bottom f f-a-c f-j-b">
			<view class="selected-container">
				<view class="selected-label">已选择:</view>
				<view class="selected-content">
					{{ selectedTitles }}
				</view>
			</view>
			<view @click="comfig" class="comfig f f-a-c f-j-c">
				确认
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				value: '李白',
				list: [],
				selectedPoems: [] // 新增：全局已选诗词
			}
		},
		computed: {
			selectedTitles() {
				const selected = this.selectedPoems.map(item => {
					return item.title.replace(/<[^>]*>/g, '');
				});
				return selected.length > 0 ? selected.join('、') : '无';
			}
		},
		onShow() {
			this.sech()
		},
		methods: {
			comfig() {
				// 获取所有选中的诗词
				const selectedPoems = this.selectedPoems;

				if (selectedPoems.length === 0) {
					uni.showToast({
						title: '请先选择诗词',
						icon: 'none'
					});
					return;
				}

				// 按照指定格式处理数据
				let formattedText = '';

				selectedPoems.forEach((poem, index) => {
					// 添加标题（去除HTML标签）
					const cleanTitle = poem.title.replace(/<[^>]*>/g, '');
					formattedText += cleanTitle;

					// 添加作者朝代（去除HTML标签）
					const cleanAuthor = poem.author.replace(/<[^>]*>/g, '');
					formattedText += '\n' + cleanAuthor;

					// 处理内容，按逗号句号分行
					const contentLines = this.splitContent(poem.content);
					contentLines.forEach(line => {
						if (line.trim()) {
							// 去除HTML标签
							const cleanLine = line.replace(/<[^>]*>/g, '').trim();
							formattedText += '\n' + cleanLine;
						}
					});
				});

				// 存储到本地
				uni.setStorageSync('formattedTexts', formattedText);

				// 提示用户
				uni.showToast({
					title: '选择成功',
					icon: 'success'
				});

				// 延迟返回上一页
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			},
			async sech() {
				if (this.value.length == 0) {
					return this.$msg('请输入搜索内容')
				}
				let n = await this.$api.articleSearch({
					keyword: this.value
				})
				n.data.forEach(item => {
					item.show = false
				})

				// 合并已选诗词和新搜索结果，保留已选状态
				const selectedIds = this.selectedPoems.map(p => p.id);
				const mergedList = n.data.map(item => {
					const idx = selectedIds.indexOf(item.id);
					if (idx !== -1) {
						item.show = true;
						return this.selectedPoems[idx]; // 用已选的对象，保持一致
					}
					return item;
				});
				this.list = mergedList;
			},
			splitContent(content) {
				// 使用正则表达式匹配中文和英文的逗号或句号，并保留标点符号
				const lines = content.split(/(?<=[，。,.！？])/);
				// 过滤掉空字符串
				return lines.filter(line => line.trim() !== '');
			},
			toggleSelect(index) {
				const item = this.list[index];
				item.show = !item.show;
				if (item.show) {
					// 添加到selectedPoems（去重）
					if (!this.selectedPoems.some(p => p.id === item.id)) {
						this.selectedPoems.push(item);
					}
				} else {
					// 取消选择，从selectedPoems移除
					this.selectedPoems = this.selectedPoems.filter(p => p.id !== item.id);
				}
			},
			parseHtmlText(htmlString) {
				// 如果没有HTML标签，直接返回原字符串
				if (!htmlString || !htmlString.includes('<')) {
					return [{
						text: htmlString,
						isHighlight: false
					}];
				}

				const result = [];
				let currentIndex = 0;

				// 使用正则表达式找到所有em标签
				const emRegex = /<em>(.*?)<\/em>/g;
				let match;

				while ((match = emRegex.exec(htmlString)) !== null) {
					// 添加em标签之前的普通文本
					if (match.index > currentIndex) {
						const normalText = htmlString.substring(currentIndex, match.index);
						if (normalText) {
							result.push({
								text: normalText,
								isHighlight: false
							});
						}
					}

					// 添加em标签内的高亮文本
					result.push({
						text: match[1],
						isHighlight: true
					});

					currentIndex = match.index + match[0].length;
				}

				// 添加最后剩余的普通文本
				if (currentIndex < htmlString.length) {
					const remainingText = htmlString.substring(currentIndex);
					if (remainingText) {
						result.push({
							text: remainingText,
							isHighlight: false
						});
					}
				}

				return result;
			}
		}
	}
</script>

<style lang="scss">
	::v-deep em {
		color: #E80000 !important;
		font-style: normal !important;
		font-weight: bold !important;
	}

	::v-deep .uicon-empty-data {
		color: #fff !important;
	}

	::v-deep .u-icon__label {
		color: #fff !important;
	}

	.consent {
		width: 100vw;
		height: 100vh;
		padding: 20rpx;
		background: linear-gradient(180deg, #05C490 0%, #00BEC8 100%);
	}

	.bottom {
		position: fixed;
		bottom: 40rpx;
		left: 0%;
		width: 100%;
		padding: 0 20rpx;
		margin-top: 10rpx;

		.comfig {
			width: 304rpx;
			height: 104rpx;
			background: #FFFFFF;
			border-radius: 30rpx;
			font-weight: 500;
			font-size: 36rpx;
			color: #333333;
		}

		.selected-container {
			display: flex;
			align-items: center;
			flex: 1;
			max-width: calc(100% - 320rpx); // 减去确认按钮的宽度
			margin-right: 20rpx;

			.selected-label {
				font-weight: 500;
				font-size: 28rpx;
				color: #FFFFFF;
				white-space: nowrap; // 防止"已选择:"换行
			}

			.selected-content {
				font-weight: 500;
				font-size: 28rpx;
				color: #FFFFFF;
				margin-left: 10rpx;
				flex: 1;
				max-height: 80rpx; // 限制高度，约2-3行
				overflow-y: auto;
				overflow-x: hidden;
				word-wrap: break-word;
				word-break: break-all;
				line-height: 1.4;

				// 隐藏滚动条
				&::-webkit-scrollbar {
					width: 0;
					height: 0;
				}

				// 兼容Firefox
				scrollbar-width: none;
				-ms-overflow-style: none;
			}
		}
	}

	.center {
		width: 100%;
		max-height: 80%;
		// background-color: pink;
		margin-top: 30rpx;
		overflow-y: auto;

		.item {
			position: relative;
			height: 420rpx;
			width: 49%;
			margin-right: 2%;
			margin-bottom: 20rpx;
			background: url('/static/ziyuan/weiSech.png') no-repeat center center;
			background-size: 100% 100%;

			.content {
				height: 80%;
				width: 80%;
				overflow-y: auto;
				display: flex;
				flex-direction: column;

				.poem-title {
					font-size: 28rpx;
					font-weight: bold;
					color: #333;
					text-align: center;
					margin-bottom: 10rpx;
				}

				.poem-author {
					font-size: 20rpx;
					color: #666;
					text-align: center;
					margin-bottom: 15rpx;
				}

				.poem-content {
					flex: 1;

					.poem-line {
						font-size: 24rpx;
						color: #333;
						line-height: 1.5;
						margin-bottom: 6rpx;
						text-align: left;
					}
				}
			}

			.content::-webkit-scrollbar {
				width: 0;
				/* 滚动条宽度 */
			}

			.dui {
				width: 48rpx;
				height: 48rpx;
				position: absolute;
				top: 30rpx;
				right: 30rpx;
			}

			&:nth-child(2n) {
				margin-right: 0;
			}
		}

		.item.seltImg {
			background: url('/static/ziyuan/sechBg.png') no-repeat center center;
			background-size: 100% 100%;
		}
	}

	.center::-webkit-scrollbar {
		width: 0;
		/* 滚动条宽度 */
	}

	/* 高亮文本样式 */
	.highlight-text {
		color: #E80000 !important;
		font-style: normal !important;
		font-weight: bold !important;
	}

	/* 搜索关键字高亮样式 - 使用标准CSS选择器 */
	.poem-title em {
		color: #E80000 !important;
		font-style: normal !important;
		font-weight: bold !important;
	}

	.poem-author em {
		color: #E80000 !important;
		font-style: normal !important;
		font-weight: bold !important;
	}

	.poem-line em {
		color: #E80000 !important;
		font-style: normal !important;
		font-weight: bold !important;
	}

	.top {
		height: 70rpx;
		width: 100%;
		padding: 0 20rpx;
		padding-right: 0;
		border-radius: 20rpx;
		border: 4rpx solid #FFFFFF;
		overflow: hidden;

		.sceh {
			height: 100%;
			width: 114rpx;
			background-color: #fff;
			font-weight: 400;
			font-size: 28rpx;
			color: #333333;
		}

		.sousuo {
			width: 28rpx;
			height: 28rpx;
			margin-right: 10rpx;

		}

		.inp {
			border: none;
			flex: 1;
			color: #FFFFFF;
			font-size: 28rpx;
			padding-left: 20rpx;
		}
	}
</style>